/**
 * 图片本地缓存
 */
APP.directive('imageCacheSave', ['$localstorage', '$timeout', function ($localstorage, $timeout) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      //元素加载完毕的方法
      element[0].onload = function () {
        var key = attr.src || attr.imageCacheSave;
        if (key.slice(0, 4) == 'data') {
          return;
        }
        //创建canvas
        var ElementCanvas = document.createElement("canvas");
        //调用画布获取上下文
        var contextCanvas = ElementCanvas.getContext("2d");
        //将元素宽高设置在canvas中
        ElementCanvas.width = element[0].width;
        ElementCanvas.height = element[0].height;
        //渲染图片到canvas中
        contextCanvas.drawImage(element[0], 0, 0, element[0].width, element[0].height);
        //用data url的形式取出
        var imgAsDataURL = ElementCanvas.toDataURL("image/png");
        // 保存到本地存储中
        $localstorage.set(key, imgAsDataURL);
      };

    }
  }
}]);

/*图片本地缓存拦截器*/
APP.filter('ImageCacheLoadFilter', ['$localstorage', function ($localstorage) {
  return function (value) {
    //如果设置ng-src或image-lazy-src属性，会在localStorage中按照对应的属性值查找是否有图片缓存
    if (value) {
      return $localstorage.get(value) || value;//有图片缓存就将缓存内容放到ng-src加载显示，如果没有显示服务器原图
    }
  }
}]);
